/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package hextd.util;

import java.awt.Color;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JLabel;

public class BlinkingLabel extends JLabel {

	private Color color1 = Color.BLACK;
	private Color color2 = Color.WHITE;
	private Color[] colors = new Color[11];
	private int step = 0;
	private boolean up = true;
	private Timer blinkTimer;
	private TimerTask blinkTask = null;

	public BlinkingLabel() {
		calculateColors();
	}

	public BlinkingLabel(Timer blinkTimer) {
		this.blinkTimer = blinkTimer;
		calculateColors();
	}

	public void setTimer(Timer timer) {
		blinkTimer = timer;
	}

	public void calculateColors() {
		for (int i = 0; i < colors.length; i++) {
			colors[i] = new Color(
					color1.getRed() + i * (color2.getRed() - color1.getRed()) / colors.length,
					color1.getGreen() + i * (color2.getGreen() - color1.getGreen()) / colors.length,
					color1.getBlue() + i * (color2.getBlue() - color1.getBlue()) / colors.length);
		}
	}

	private void nextStep() {
		if (up) {
			step++;
			if (step >= 10) {
				up = false;
			}
		} else {
			step--;
			if (step <= 0) {
				up = true;
			}
		}
		setForeground(colors[step]);
	}

	public void startBlinking() {
		if (blinkTimer == null) {
			blinkTimer = new Timer("BlinkingLabelTimer", true);
		}
		if (blinkTask == null) {
			blinkTask = new TimerTask() {

				@Override
				public void run() {
					nextStep();
				}
			};
			blinkTimer.schedule(blinkTask, 100, 100);
		}
	}

	public void stopBlinking() {
		if (blinkTask != null) {
			blinkTask.cancel();
		}
		blinkTask = null;
		step = 1;
		up = false;
		nextStep();
	}

	/**
	 * @return the color1
	 */
	public Color getColor1() {
		return color1;
	}

	/**
	 * @param color1 the color1 to set
	 */
	public void setColor1(Color color1) {
		this.color1 = color1;
		calculateColors();
	}

	/**
	 * @return the color2
	 */
	public Color getColor2() {
		return color2;
	}

	/**
	 * @param color2 the color2 to set
	 */
	public void setColor2(Color color2) {
		this.color2 = color2;
		calculateColors();
	}
}
